import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Response as ExpressResponse } from 'express';

export interface Response<T> {
  code: number;
  message: string;
  data: T | null; // 修改为直接包含数据
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((rawData) => {
        const data = typeof rawData !== 'undefined' ? (rawData as T) : null;

        return {
          code: 200,
          message: 'success',
          data, // 数据直接放在data字段
        };
      }),
    );
  }
}
